package com.bailian.app.interceptor;

import com.bailian.app.service.WechatMiniProgramService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 认证拦截器
 * 
 * @author bailian
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    @Autowired
    private WechatMiniProgramService wechatService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        logger.debug("处理认证请求: {} {}", request.getMethod(), requestURI);
        
        // 获取token - 支持多种方式
        String token = request.getHeader("Authorization");
        
        if (token == null || token.isEmpty()) {
            // 尝试从参数获取
            token = request.getParameter("token");
        }
        
        // 处理Bearer前缀
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        // 验证token
        if (token == null || token.isEmpty()) {
            logger.warn("Token为空，请求被拒绝: {}", requestURI);
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"请求访问：" + requestURI + "，认证失败，token不能为空\"}");
            return false;
        }
        
        // 验证token有效性
        if (!wechatService.validateToken(token)) {
            logger.warn("Token验证失败，请求被拒绝: {}", requestURI);
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"请求访问：" + requestURI + "，认证失败，token无效\"}");
            return false;
        }
        
        // 将用户ID存储到request中
        Long userId = wechatService.getUserIdFromToken(token);
        request.setAttribute("userId", userId);
        logger.debug("认证成功，用户ID: {}", userId);
        
        return true;
    }
} 